package org.pierre.inputbenchmark.activity;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.pierre.inputbenchmark.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.TextView;

public class MultitouchBenchmarkActivity extends Activity
{
	private static Method mMotionEvent_getPointerCount = null;
	private static Method mMotionEvent_getX_int = null;
	private static Method mMotionEvent_getY_int = null;
	
	private StringBuilder result;
	private TextView resultText;
	private String pointDetectedString;
	
	static
	{
		checkMultitouchAvailable();
	}
	
	private static void checkMultitouchAvailable()
	{
		try
		{
			mMotionEvent_getPointerCount = MotionEvent.class.getMethod("getPointerCount");
			mMotionEvent_getX_int = MotionEvent.class.getMethod("getX", int.class);
			mMotionEvent_getY_int = MotionEvent.class.getMethod("getY", int.class);
		}
		catch (NoSuchMethodException e)
		{
		}
	}
	
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		this.setContentView(R.layout.multitouch);
		
		this.result = new StringBuilder();
		this.resultText = (TextView) this.findViewById(R.id.multitouch_result);
		
		TextView multitouchAvailableText = (TextView) this.findViewById(R.id.multitouch_available);
		int res;
		if (mMotionEvent_getPointerCount != null)
		{
			res = R.string.multitouch_available;
		}
		else
		{
			res = R.string.multitouch_not_available;
		}
		multitouchAvailableText.setText(this.getResources().getString(res));
		
		this.pointDetectedString = " " + this.getResources().getString(R.string.point_detected) + "\n";
	}
	
	public synchronized boolean onTouchEvent(MotionEvent event)
	{
		if (event.getAction() != MotionEvent.ACTION_UP)
		{
			if (mMotionEvent_getPointerCount != null)
			{
				try
				{
					int pointerCount = (Integer) mMotionEvent_getPointerCount.invoke(event);
					this.result.append(pointerCount + this.pointDetectedString);
					
					for (int i = 0; i < pointerCount; i++)
					{
						this.result.append("X" + i + "=" + mMotionEvent_getX_int.invoke(event, i) + " Y" + i + "=" + mMotionEvent_getY_int.invoke(event, i) + "\n");
					}
				}
				catch (IllegalArgumentException e)
				{
					e.printStackTrace();
				}
				catch (IllegalAccessException e)
				{
					e.printStackTrace();
				}
				catch (InvocationTargetException e)
				{
					e.printStackTrace();
				}
			}
			else
			{
				this.result.append("1" + this.pointDetectedString);
				this.result.append("X0=" + event.getX() + " Y0=" + event.getY());
			}
		}
		else
		{
			this.result.append("0" + this.pointDetectedString);
		}
		
		this.resultText.setText(this.result.toString());
		this.result.delete(0, this.result.length());
		
		return true;
	}
}
